<template>
  <el-dialog :visible.sync="uploadDialog" width="30%" :before-close="closeFn">
    <div class="dialog-title" slot="title">
      <span>{{ dialogTitle }}</span>
      <span
        v-if="templateUrl"
        class="text-red margin-left pointer"
        @click="downloadTemplate"
        >下载导入模板</span
      >
    </div>

    <el-upload
      class="upload-demo"
      drag
      ref="upload"
      :action="actionUrl"
      multiple
      :auto-upload="false"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :http-request="uploadFn"
      :on-change="onChange"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip" v-if="fileType">
        只能上传{{ fileType === "img" ? "jpg/png" : "excel" }}文件，且不超过5MB
      </div>
      <!-- <el-button slot="trigger" size="small" type="primary">选取文件</el-button> -->
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="submitUpload">上传到服务器</el-button>
    </span>
  </el-dialog>
</template>

<script>
// import request from '@/utils/request'
// import { getToken } from '@/utils/auth'
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { untransform } from "@/store/yg/common/uri";
import * as constant from "@/store/yg/common/constant";
export default {
  name: "ImportPop",
  props: {
    waybillId: {
      type: Number,
      default: 1
    },
    // 显示弹窗
    uploadDialog: {
      type: Boolean,
      default: false
    },
    // 弹窗标题
    dialogTitle: {
      type: String,
      default: "批量导入"
    },
    // 是否多选
    isMultiple: {
      type: Boolean,
      default: true
    },
    // 文件类型限制
    fileType: {
      type: String,
      default: ""
    },
    // 下载模板Url
    templateUrl: {
      type: String,
      default: ""
    },
    // 上传Url
    actionUrl: {
      type: String,
      default: "#"
    },
    // 上传Url
    fileName: {
      type: String,
      default: "templateFile"
    }
  },

  data() {
    return {
      fileList: []
    };
  },

  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log("handlePreview", file);
    },
    onChange(file, fileList) {
      console.log("onChange", file, fileList);
      this.fileList = fileList;
    },

    beforeUpload(file) {
      console.log("beforeUpload");
      switch (this.fileType) {
        case "excel":
          const isEXCEL =
            file.type === "application/vnd.ms-excel" ||
            file.type ===
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
          if (!isEXCEL) {
            this.$message.error("上传文件只能是EXCEL文件!");
            return false;
          }
          break;

        case "img":
          const isJPG = file.type === "image/jpeg";
          const isPng = file.type === "image/png";
          if (!isJPG && !isPng) {
            this.$message.error("上传文件只能是jpg/png文件!");
            return false;
          }
          break;

        default:
          break;
      }

      const isLt1M = file.size / 1024 / 1024 < 5;

      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 5MB!");
        return false;
      }

      return true;
    },
    closeFn() {
      this.fileList = [];
      this.$emit(`update:uploadDialog`, false);
    },

    async uploadFn(params) {
      console.log("params", params);
      // if (!this.beforeUpload(params.file)) return
      const formData = new FormData();
      // 通过 FormData 对象上传文件
      this.formData.append(this.fileName, params.file);
      console.log("this.waybillId :>> ", this.waybillId);
      if (this.waybillId) {
        formData.append("waybillId", this.waybillId);
      }

      this.submitUpload();
    },
    async submitUpload(params) {
      console.log("params", params);
      // if (!this.beforeUpload(params.file)) return;
      if (this.fileList.length === 0) {
        this.$message.error("请上传文件");
        return false;
      }
      // 通过 FormData 对象上传文件
      const formData = new FormData();
      // 通过 FormData 对象上传文件
      for (const i of this.fileList) {
        if (await this.beforeUpload(i.raw)) {
          formData.append("items[]", i.raw);
        }
      }
      if (this.waybillId) {
        formData.append("waybillId", this.waybillId);
      }
      console.log("files", formData.getAll("files"));

      const action = `${
        constant.API_SERVER
      }/api/consume/upload?uri=${untransform(this.$route.params.uri)}&f=${
        this.actionUrl
      }&type=blank`;
      console.log("action :>> ", action);

      const { data } = await axios({
        url: action,
        method: "post",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data"
        }
      });

      console.log("data :>> ", data);
      if (data.code === 200) {
        this.$message({
          message: "导入成功！",
          type: "success"
        });
        setTimeout(() => {
          location.reload();
        }, 2000);
        this.$emit(`update:uploadDialog`, false);
        this.$emit(`uploadCb`, data.data);
      } else {
        this.$message({
          dangerouslyUseHTMLString: true,
          type: "error",
          message:
            data.message ||
            data.errorTips ||
            data.formatTips ||
            data.error ||
            "上传失败！"
        });
      }
      this.fileList = [];
    },
    downloadTemplate() {
      console.log("downloadTemplate:下载模板");
    }
  }
};
</script>

<style></style>
